import Vue from 'vue';
import Anchor from './directives/autoAnchor/Anchor.vue';
import { initLazyIntersectionobserver } from './util'

let timer, times = 0
function genTitles(el) {
  const idstr = el.getAttribute('data-anchor')
  let idNames
  if (idstr) {
    idNames = JSON.parse(idstr)
  } else {
    return [[], {}]
  }
  const panels = [];
  let titles = idNames.map(idName => {
    const child = el.querySelector('#' + idName.id)
    child && panels.push(child)
    return child ? { titleId: idName.id, title: idName.name || '未配置标题' } : {};
  });
  titles = titles.filter(title => title && title.titleId)
  return [panels, titles];
}

function __anchorUpdate() {
  clear(this)
  renderAnchor(this)
}

function renderAnchor(el) {
  const Anchorconstruct = Vue.extend(Anchor);
  const [panels, titles] = genTitles(el);
  if (panels.length === 0) {
    timer && clearTimeout(timer)
    timer = setTimeout(() => {
      times++
      times === 3 && clearTimeout(timer)// 只尝试三次
      renderAnchor(el)
    }, 600)
    return
  }
  el.panels = panels;
  const instance = new Anchorconstruct({ propsData: { titles } });
  const observer = initLazyIntersectionobserver((entry) => {
    if (instance.click === true) {
      return
    }
    if (entry.isIntersecting) {
      instance.current = entry.target.id
    }
  });
  el.observer = observer;
  el.anthorvue = instance;
  instance.$mount();
  instance.observer = observer
  panels.forEach((item) => {
    observer.observe(item);
  })
  el.appendChild(instance.$el);
}

function clear(el) {
  if (el) {
    el.panels && el.panels.forEach(panel => el.observer.unobserve(panel))
    if (el.anthorvue) {
      el.anthorvue.$el && el.anthorvue.$el.parentNode.removeChild(el.anthorvue.$el)
      el.anthorvue.$destroy()
      el.panels = null
    }
    el.panels = null
  }
}

export default {
  inserted(el) {
    renderAnchor(el);
  },
  unbind(el) {
    clear(el);
  },
  componentUpdated(el) {
    __anchorUpdate.call(el)
  }
}